<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="申请时间" prop="useTime" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_record_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 308px">
              <el-date-picker
                v-model="createTimeRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:admCarReimburse:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:admCarReimburse:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:admCarReimburse:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:admCarReimburse:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="admCarReimburseList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="用车人" align="center" prop="applyId" >
          <template #default="scope">
            <el-tooltip :content="scope.row.applyName" placement="top" :disabled="!scope.row.applyName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.applyName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="车牌" align="center" prop="carId" width="220">
          <template #default="scope">
            <el-tooltip :content="scope.row.carName" placement="top" :disabled="!scope.row.carName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.carName || "未设置" }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="报销时间段" align="center" prop="reimburstmentTime" width="300"/>
        <el-table-column label="车辆性质" align="center" prop="carType" >
          <template #default="scope">
            <dict-tag :options="car_type_options" :value="scope.row.carType" />
          </template>
        </el-table-column>
        <el-table-column label="报销费用" align="center" prop="reimburstmentExpenses" />
        <el-table-column label="审批状态" align="center" prop="status" >
          <template #default="scope">
            <dict-tag :options="approval_record_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark">
          <template #default="scope">
            <el-tooltip :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.remark }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:admCarReimburse:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:admCarReimburse:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改车辆报销对话框 -->
    <el-dialog 
      :title="dialog.title" 
      v-model="dialog.visible" 
      width="900px" 
      append-to-body
      class="seal-dialog"
    >
      <template #default>
        <el-form ref="admCarReimburseFormRef" :model="form" :rules="rules" label-width="140px" label-position="left" style="padding: 20px 0 20px 24px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="申请人" prop="applyId">
                <el-input v-model="form.applyName" placeholder="请输入申请人id" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="部门" prop="deptId">
                <el-tree-select
                    v-model="form.deptId"
                    :data="deptTree"
                    placeholder="请选择入库部门"
                    :props="{ label: 'label', value: 'id', children: 'children' }"
                    check-strictly
                    filterable
                    :default-expand-all="true"
                    style="width: 100%"
                    @visible-change="handleVisibleChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="申请日期" prop="applyTime">
                <el-date-picker clearable
                  v-model="form.applyTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择申请日期"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="车辆" prop="carId">
                <el-select
                  v-model="form.carId"
                  placeholder="请选择车辆"
                  filterable
                  @change="onCarChange"
                >
                  <el-option
                    v-for="car in carList"
                    :key="car.id"
                    :label="`${car.model} (${car.carNumber})`"
                    :value="car.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="选择报销记录" prop="selectedRecords">
                <el-select
                  v-model="flatRecords"
                  multiple
                  filterable
                  placeholder="请选择记录"
                  ref="selectRecordsRef"
                >
                  <!-- 有可选记录时正常渲染 -->
                  <el-option
                    v-for="group in applyList"
                    :key="group.pid"
                    :label="group.name"
                    :value="group.pid"
                    :disabled="group.disabled || false"
                  />
                  <!-- 没有可选记录时显示默认提示 -->
                  <el-option
                    v-if="applyList.length === 0"
                    :label="'当前时间段没有可报销记录'"
                    :value="null"
                    disabled
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="报销时间段" prop="reimburstmentTime">
                <el-date-picker
                  v-model="form.reimburstmentTime"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  @change="filterByTime"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="报销费用" prop="reimburstmentExpenses">
                <el-input v-model="form.reimburstmentExpenses" placeholder="请输入报销费用" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="车辆性质" prop="carType">
                <el-input
                  :model-value="carTypeMap[form.carType] || '未知'"
                  placeholder="车辆性质"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AdmCarReimburse" lang="ts">
import { listAdmCarReimburse, getAdmCarReimburse, delAdmCarReimburse, addAdmCarReimburse, updateAdmCarReimburse, getListByUser } from '@/api/general/administration/car/reimburse';
import { AdmCarReimburseVO, AdmCarReimburseQuery, AdmCarReimburseForm  } from '@/api/general/administration/car/reimburse/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';
import { AdmCarApplyVO, RecordItem, RecordGroup } from '@/api/general/administration/car/apply/types';
import dayjs from "dayjs"
import { queryListByUser } from '@/api/general/administration/car/drive';
import { queryCanInfo } from '@/api/general/administration/car/store';
import { AdmCarStoreDto } from '@/api/general/administration/car/store/types';
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const admCarReimburseList = ref<AdmCarReimburseVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();

// 用户信息
const userStore = useUserStore();

// 引入数据字典
const { car_type_options, approval_record_status } = toRefs<any>(proxy?.useDict('car_type_options', 'approval_record_status'));

// 初始化申请表
const applyList = ref<RecordGroup[]>([]);
const selectRecordsRef = ref<InstanceType<typeof import('element-plus').ElSelect> | null>(null);
// 扁平化所有 records，方便循环显示
const flatRecords = ref<any[]>([]); // 这里使用 ref 而不是 computed
const originalList = ref([]) // 保存原始数据，不被过滤破坏
// 已选分组（后台返回的修改数据）
const selectedList = ref<any[]>([])

const carList = ref<any[]>([]);
const carTypeMap = {
  0: '私车',
  1: '公车',
  2: '租车'
};

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);


const queryFormRef = ref<ElFormInstance>();
const admCarReimburseFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: AdmCarReimburseForm = {
  id: undefined,
  applyId: userStore.userId,
  applyName: userStore.name,
  applyTime: formatLocalDate(),
  recordIds: [],
  applyIds: [],
  recordStr: undefined,
  number: undefined,
  deptId: userStore.deptId,
  deptName: userStore.deptName,
  carId: undefined,
  carName: undefined,
  reimburstmentTime: [] as string[],
  carType: undefined,
  reimburstmentExpenses: undefined,
  remark: undefined,
  status: undefined,
}
const data = reactive<PageData<AdmCarReimburseForm, AdmCarReimburseQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    applyId: undefined,
    applyName: undefined,
    applyTime: undefined,
    number: undefined,
    deptId: undefined,
    deptName: undefined,
    carId: undefined,
    carName: undefined,
    reimburstmentTime: undefined,
    carType: undefined,
    reimburstmentExpenses: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    applyId: [
      { required: true, message: '申请人不能为空', trigger: 'blur' }
    ],
    deptId: [
      { required: true, message: '请选择入库部门', trigger: 'change' }
    ],
    applyTime: [
      { required: true, message: '请选择申请日期', trigger: 'change' }
    ],
    carId: [
      { required: true, message: '请选择车辆行程', trigger: 'change' }
    ],
    reimburstmentTime: [
      { required: true, message: '请选择报销时间段', trigger: 'change' },
      {
        validator: (rule, value, callback) => {
          if (!value || value.length !== 2) {
            return callback(new Error('请选择完整的报销时间段'));
          }
          const [start, end] = value;
          if (new Date(end) < new Date(start)) {
            return callback(new Error('报销结束时间不能早于开始时间'));
          }
          callback();
        },
        trigger: 'change'
      }
    ],
    reimburstmentExpenses: [
      { required: true, message: '请输入报销费用', trigger: 'blur' },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: '报销费用必须为有效数字，最多两位小数',
        trigger: 'blur'
      }
    ],
    carType: [
      { required: true, message: '车辆性质不能为空', trigger: 'blur' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询车辆报销列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listAdmCarReimburse(params);
    admCarReimburseList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  flatRecords.value = [];
  admCarReimburseFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
    queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdmCarReimburseVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加车辆报销";
  // 新增不立刻计算报销金额
  selectedList.value = [];
  flatRecords.value = [];
  applyList.value = [...originalList.value];
}


/** 修改按钮操作 */
const handleUpdate = async (row?: AdmCarReimburseVO) => {
  reset()
  const _id = row?.id || ids.value[0]
  const res = await getListByUser(_id)
  const { admCarReimburse, data } = res.data
  // 1. 主表字段
  Object.assign(form.value, {
    ...admCarReimburse,
    reimburstmentExpenses: Number(admCarReimburse.reimburstmentExpenses),
    remark: admCarReimburse.remark || ''
  })
  // 2. 时间段（不赋值到表单，避免影响下拉框展示）
  form.value.reimburstmentTime = [null, null]
  // 3. 已选分组 & 可选分组
  selectedList.value = data
    .filter(g => g.selected === 1) // 已选
    .map(group => ({
      ...group,
      minUseTime: group.minUseTime ? dayjs(group.minUseTime).format('YYYY-MM-DD') : '',
      maxBackTime: group.maxBackTime ? dayjs(group.maxBackTime).format('YYYY-MM-DD') : '',
      name: `${group.name.split('(')[0]}(${group.minUseTime}~${group.maxBackTime})`,
      records: group.records.map(r => ({ ...r, disabled: true }))
    }))
  // 4. 下拉框展示全部记录（已选 + 可选）
  applyList.value = data.map(group => ({
    ...group,
    minUseTime: group.minUseTime ? dayjs(group.minUseTime).format('YYYY-MM-DD') : '',
    maxBackTime: group.maxBackTime ? dayjs(group.maxBackTime).format('YYYY-MM-DD') : '',
    name: `${group.name.split('(')[0]}(${group.minUseTime}~${group.maxBackTime})`,
    records: group.records.map(r => ({ ...r, disabled: group.selected === 1 })),
    disabled: group.selected === 1
  }))
  // 5. 回显已选记录
  flatRecords.value = selectedList.value.map(g => g.pid)
  // 6. 根据已选记录计算报销金额、时间范围
  recalcForm()
  dialog.visible = true
  dialog.title = "修改车辆报销"
  console.log('[handleUpdate] applyList:', applyList.value.map(g => ({ pid: g.pid, disabled: g.disabled })))
  console.log('[handleUpdate] flatRecords:', flatRecords.value)
}



/** 提交按钮 */
const submitForm = () => {
  admCarReimburseFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    buttonLoading.value = true;
    try {
      // 扁平化所有勾选的记录 ID (selected === 1)
      const recordStr = applyList.value
        .filter(group => flatRecords.value.includes(group.pid)) // 选中的分组
        .flatMap(group => group.records.map(r => r.id))          // 取每条记录 ID
        .join(',');
      console.log('提交 recordStr:', recordStr);

      // 构造提交对象
      const { reimburstmentTime, applyIds, ...rest } = form.value; 
      const payload = {
        ...rest,
        recordStr, // 逗号分隔字符串
        applyIds: undefined, // 不传二维数组
        reimburstmentTimeStr: reimburstmentTime && reimburstmentTime.length === 2
          ? `${reimburstmentTime[0]} ~ ${reimburstmentTime[1]}`
          : ''
      };

      if (payload.id) {
        await updateAdmCarReimburse(payload);
      } else {
        await addAdmCarReimburse(payload);
      }

      proxy?.$modal.msgSuccess('操作成功');
      reset();
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};


/** 删除按钮操作 */
const handleDelete = async (row?: AdmCarReimburseVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除车辆报销编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAdmCarReimburse(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/admCarReimburse/export', {
    ...queryParams.value
  }, `admCarReimburse_${new Date().getTime()}.xlsx`)
}

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
       tree?.expandAll?.();
    }, 0);
  }
};


// 车辆选择变化时重新初始化 applyList
const onCarChange = async (carId: number) => {
  form.value.carId = carId
  await initApplyList()
  filterByTime()
  recalcForm()
}

// 获取车辆全部信息
const getCarList = async () => {
  try {
    const param: AdmCarStoreDto = {
      isLend: '0',
      status: 1,
      // 其他字段根据需要添加
    };
    const response = await queryCanInfo(param);
    carList.value = response.data || [];
  } catch (error) {
    console.error('获取车辆列表失败:', error);
    proxy?.$modal.msgError('获取车辆列表失败');
  }
};


// 初始化车辆可选分组
const initApplyList = async () => {
  if (!form.value.carId) return
  const res = await queryListByUser(userStore.userId, userStore.deptId, form.value.carId)
  originalList.value = (res.data || []).map(group => ({
    ...group,
    minUseTime: dayjs(group.minUseTime).format('YYYY-MM-DD'),
    maxBackTime: dayjs(group.maxBackTime).format('YYYY-MM-DD'),
    name: `${group.name.split('(')[0]}(${dayjs(group.minUseTime).format('YYYY-MM-DD')}~${dayjs(group.maxBackTime).format('YYYY-MM-DD')})`,
    pid: group.pid,
    id: group.id,
    disabled: false // 新增记录默认可选
  }))
}

// 根据时间段过滤 applyList（已选 + 可选）
const filterByTime = () => {
  const [start, end] = form.value.reimburstmentTime || []
  let filteredOriginal = originalList.value
  if (start && end) {
    filteredOriginal = originalList.value.filter(g =>
      dayjs(g.minUseTime).isSameOrAfter(start) &&
      dayjs(g.maxBackTime).isSameOrBefore(end)
    )
  }
  // applyList 显示已选 + 可选
  applyList.value = [...selectedList.value, ...filteredOriginal]
  console.log("applyList",applyList.value)
  // 重新生成 flatRecords，用于表单计算
  flatRecords.value = applyList.value.map(g => g.pid)
  // ⚡ 仅在有选中记录时计算总金额
  if (flatRecords.value.length > 0) {
    recalcForm()
  }
}


// 重新计算报销总金额、carType、记录 ID
const recalcForm = () => {
  console.log('[recalcForm] flatRecords:', flatRecords.value)
  console.log('[recalcForm] applyList:', applyList.value.map(g => ({ pid: g.pid, name: g.name })))

  // 选中的记录
  let selectedForForm = applyList.value.filter(g => flatRecords.value.includes(g.pid))
  console.log('[recalcForm] selectedForForm before time filter:', selectedForForm.map(g => g.pid))
  const [start, end] = form.value.reimburstmentTime || []
  if (!selectedForForm.length) {
    form.value.reimburstmentExpenses = 0
    form.value.carType = undefined
    form.value.recordIds = []
    form.value.applyIds = []
    console.log('[recalcForm] no selected records')
    return
  }
  const minUseTime = selectedForForm.map(g => g.minUseTime).sort()[0]
  const maxBackTime = selectedForForm.map(g => g.maxBackTime).sort().reverse()[0]
  form.value.reimburstmentTime = [minUseTime, maxBackTime]
  const totalAmount = selectedForForm.reduce((sum, g) => sum + Number(g.totalAmount || 0), 0)
  form.value.reimburstmentExpenses = Number(totalAmount.toFixed(2))
  form.value.carType = Number(selectedForForm[0].type)
  form.value.recordIds = selectedForForm.map(g => Number(g.id))
  form.value.applyIds = selectedForForm.map(g => g.recordIds)
  console.log('[recalcForm] form:', {
    reimburstmentTime: form.value.reimburstmentTime,
    reimburstmentExpenses: form.value.reimburstmentExpenses,
    recordIds: form.value.recordIds,
    applyIds: form.value.applyIds
  })
}



// 监听 flatRecords 变化，重新计算表单
watch(flatRecords, () => {
  recalcForm()
}, { deep: true })

watch(applyList, (val) => {
  if (val.length === 0 && selectRecordsRef.value) {
    console.log('[watch applyList] no records, open select')
    
    // 延迟展开，保证 DOM 已渲染
    nextTick(() => {
      selectRecordsRef.value?.toggleMenu()
    })
  }
}, { immediate: true })



onMounted(async () => {
  getList();
  fetchDeptTree();
  getCarList();
});
</script>
<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto !important;
  display: block; /* 确保是块级元素 */
}
</style>